package com.wing.bill.scheduler;

import com.wing.bill.model.entity.BillDetailInfo;
import com.wing.bill.model.entity.WarehouseBill;
import com.wing.bill.model.entity.WarehouseBillDetail;
import com.wing.bill.service.WarehouseBillDetailService;
import com.wing.bill.service.WarehouseBillService;
import com.wing.product.model.entity.WarehouseProductInventory;
import com.wing.product.service.WarehouseProductInventoryService;
import com.wing.user.service.WarehouseUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Component
public class WarehouseBillScheduler {
    @Autowired
    WarehouseBillDetailService warehouseBillDetailService;
    @Autowired
    WarehouseBillService warehouseBillService;
    @Autowired
    WarehouseProductInventoryService warehouseProductInventoryService;


//    @Scheduled(cron = "*/30 * * * * ?")
    @Scheduled(cron = "0 5 0 1 * ?")
    private void billScheduler(){
        // 结算上月所有账单
        if(warehouseBillDetailService.updateAllBillDetail()){
            // 获取所有在库产品
           List<WarehouseProductInventory> productInventoryList = warehouseProductInventoryService.getAllProductInventory();

           List<Long> customerIdList = getUniqueCustomerIds(productInventoryList);
                for(Long id : customerIdList){
                    WarehouseBill bill = warehouseBillService.createBill(id);
                    warehouseBillDetailService.addBillDetail(bill.getCustomerId(),getSystBundleCodeList(productInventoryList,id),bill.getId());
                }

        }
    }

    private static List<Long> getUniqueCustomerIds(List<WarehouseProductInventory> list) {
        return list.stream()
                .map(WarehouseProductInventory::getCustomerId)
                .filter(Objects::nonNull) // 如果可能有 null 值，可以过滤掉
                .distinct()              // 去重
                .collect(Collectors.toList());
    }

    private static List<BillDetailInfo> getSystBundleCodeList(List<WarehouseProductInventory> list, Long id) {
        return list.stream()
                .filter(product -> id.equals(product.getCustomerId()))
                .map(product -> {
                    BillDetailInfo detailInfo = new BillDetailInfo();
                    detailInfo.setSysBundleCode(product.getSysBundleCode());
                    detailInfo.setPrice(product.getPrice());
                    return detailInfo;
                })
                .collect(Collectors.toList());
    }
}
